package com.bawei.mall.product.service.impl;

import com.bawei.common.core.constant.IndexNameConstants;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.DateUtils;
import com.bawei.common.core.utils.bean.BeanUtils;
import com.bawei.common.rabbit.domain.Message;
import com.bawei.common.rabbit.enums.QueueEnum;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.domain.query.DocDeleteReq;
import com.bawei.domain.request.DocInfoReq;
import com.bawei.mall.product.cache.ProductInfoCache;
import com.bawei.mall.product.domain.MallProductEsInfo;
import com.bawei.mall.product.domain.MallProductInfo;
import com.bawei.mall.product.domain.MallProductRuleInfo;
import com.bawei.mall.product.domain.MallProductSkuInfo;
import com.bawei.mall.product.domain.model.ProductModel;
import com.bawei.mall.product.domain.model.SkuModel;
import com.bawei.mall.product.domain.reponse.ProductDetailsResponse;
import com.bawei.mall.product.domain.reponse.ProductInfoResponse;
import com.bawei.mall.product.domain.request.ProductInfoRequest;
import com.bawei.mall.product.enums.SaleStatus;
import com.bawei.mall.product.mapper.MallProductInfoMapper;
import com.bawei.mall.product.mapper.MallProductSkuInfoMapper;
import com.bawei.mall.product.service.IMallProductInfoService;
import com.bawei.mall.product.service.IMallProductRuleInfoService;
import com.bawei.mall.product.service.IMallProductSkuInfoService;
import com.bawei.remote.api.RemoteEsDocService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品信息Service业务层处理
 *
 * @author DongZeLiang
 * @date 2022-09-19
 */
@Service
public class MallProductInfoServiceImpl implements IMallProductInfoService {
    @Autowired
    private MallProductInfoMapper mallProductInfoMapper;

    @Autowired
    private IMallProductSkuInfoService skuInfoService;

    @Autowired
    private IMallProductRuleInfoService ruleInfoService;


    @Autowired
    private ProductInfoCache productInfoCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private RemoteEsDocService remoteEsDocService;

    @Autowired
    private MallProductSkuInfoMapper mallProductSkuInfoMapper;


    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    @Override
    public ProductInfoResponse selectMallProductInfoById(Long id) {
        MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
        ProductInfoResponse productInfoResponse = new ProductInfoResponse();
        BeanUtils.copyBeanProp(productInfoResponse, mallProductInfo);
        productInfoResponse.setSkuInfoList(
                skuInfoService.selectMallProductSkuInfoList(new MallProductSkuInfo() {{
                    setProductId(id);
                }})
        );
        return productInfoResponse;
    }

    @Override
    public ProductDetailsResponse selectProductDetailsById(Long productId) {
        if (productId == null || productId == 0) {
            throw new ServiceException("查询商品信息，依据不合法！");
        }
        ProductDetailsResponse productDetailsResponse = new ProductDetailsResponse();
        ProductModel productModel = mallProductInfoMapper.selectProductModelById(productId);
        if (productModel == null) {
            throw new ServiceException("查询商品信息，商品数据为空");
        }
        productDetailsResponse.setProduct(productModel);
        List<MallProductSkuInfo> mallProductSkuInfos = skuInfoService.selectMallProductSkuInfoList(productId);
        if (mallProductSkuInfos == null || mallProductSkuInfos.size() == 0) {
            throw new ServiceException("查询商品信息，SKU数据为空");
        }
        productDetailsResponse.setSkuList(mallProductSkuInfos);
        MallProductRuleInfo ruleInfo = ruleInfoService.selectMallProductRuleInfoById(productModel.getRuleId());
        if (ruleInfo == null) {
            throw new ServiceException("查询商品信息，规格数据为空");
        }
        productDetailsResponse.setProductRule(ruleInfo);
        return productDetailsResponse;
    }

    /**
     * 查询商品信息列表
     *
     * @param mallProductInfo 商品信息
     * @return 商品信息
     */
    @Override
    public List<MallProductInfo> selectMallProductInfoList(MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoList(mallProductInfo);
    }

    /**
     * 新增商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMallProductInfo(ProductInfoRequest productInfoRequest) {
        productInfoRequest.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setCreateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.insertMallProductInfo(productInfoRequest);
        if (i == 0) {
            return i;
        }

        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );

        // 给搜索系统发送消息需要进行搜索更新
        rabbitTemplate.convertAndSend(QueueEnum.PRODUCT_ADD.queueName(),
                Message.builderMsg(productInfoRequest.getId()));

        return i;
    }

    /**
     * 修改商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateMallProductInfo(ProductInfoRequest productInfoRequest) {
        productInfoRequest.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setUpdateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.updateMallProductInfo(productInfoRequest);
        if (i == 0) {
            return i;
        }
        skuInfoService.deleteMallProductSkuInfoByProductId(productInfoRequest.getId());
        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );
        return i;
    }

    /**
     * 批量删除商品信息
     * @param ids 需要删除的商品信息主键
     */
    @Override
    public int deleteMallProductInfoByIds(Long[] ids) {
        skuInfoService.deleteMallProductSkuInfoByProductIds(ids);
        for (Long id : ids) {
            // 延迟执行
            productInfoCache.delayRemove(id);
        }
        return mallProductInfoMapper.deleteMallProductInfoByIds(ids);
    }

    /**
     * 删除商品信息信息
     *
     */
    @Override
    public int deleteMallProductInfoById(Long id) {
        return mallProductInfoMapper.deleteMallProductInfoById(id);
    }


    /**
     * 商品总条数
     *
     * @param mallProductInfo 商品查询
     * @return
     */
    @Override
    public Long selectMallProductInfoCount(MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoCount(mallProductInfo);
    }

    @Override
    public void sale(Long productId, Integer status) {

        R result=null;

        String message;

        if (status.equals(SaleStatus.ON.getCode())) {
            //根据Id查询商品
            ProductDetailsResponse productDetail = selectProductDetailsById(productId);
            //检验商品信息
            checkProductDetail(productDetail);
            //组装上架信息
            List<MallProductEsInfo> productInfo = assembleProduct(productDetail);
            DocInfoReq docInfoReq=assembleDocInfoReq(productInfo);

            //远程调用Es服务上架商品
           result=remoteEsDocService.createDoc(docInfoReq);

           message="商品上架成功";

        } else {
            //远程调用Es服务下架商品
            List<Long> skuIds = mallProductInfoMapper.getSkuidByPid(productId);
            DocDeleteReq docDeleteReq = assembleDocDeleteReq(skuIds);
            result= remoteEsDocService.delete(docDeleteReq);
            message="商品下架成功";
        }
        if(200!=result.getCode()){
            throw new ServiceException("商品下架失败");
        }

    }

    private DocDeleteReq assembleDocDeleteReq(List<Long> skuIds) {

        DocDeleteReq docDeleteReq = new DocDeleteReq();
        docDeleteReq.setIndexName(IndexNameConstants.INDEX_NAME);
        docDeleteReq.setIds(skuIds);
        return docDeleteReq;

    }

    private DocInfoReq assembleDocInfoReq(List<MallProductEsInfo> productInfo) {
        DocInfoReq result = new DocInfoReq();
        result.setIndexName(IndexNameConstants.INDEX_NAME);
        result.setNeedId(true);
        result.setIdField("skuId");

        //将MallProductInfo转成Map<String,Object>
        ArrayList<Map<String, Object>> docs = new ArrayList<>();
        for (MallProductEsInfo productEsInfo : productInfo) {
            HashMap<String, Object> doc = new HashMap<>();
            BeanUtils.copyProperties(productEsInfo,doc);
            docs.add(doc);
        }
        //转JSON类型
//        String jsonString = JSONObject.toJSONString(productInfo);
//        List<Map<String,Object>> list = JSONObject.parseObject(jsonString, List.class);
//        result.setDatas(list);

        result.setDatas(docs);
        return result;
    }

    private List<MallProductEsInfo> assembleProduct(ProductDetailsResponse productDetail) {
        //构建返回提
        ArrayList<MallProductEsInfo> result = new ArrayList<>();
        //获取商品信息
        ProductModel product = productDetail.getProduct();
        //获取商品规格信息
        List<MallProductSkuInfo> skuList = productDetail.getSkuList();
        for (MallProductSkuInfo mallProductSkuInfo : skuList) {
            MallProductEsInfo productInfo = new MallProductEsInfo();

            BeanUtils.copyProperties(product, productInfo);
            String skus = assembleSku(mallProductSkuInfo);
            productInfo.setSkus(skus);
            //将字典转化为汉字
            assembleDict(productInfo);
            result.add(productInfo);
        }

        return result;
    }

    private void assembleDict(MallProductEsInfo productInfo) {
        //封装字典
    }

    private String assembleSku(MallProductSkuInfo mallProductSkuInfo) {
        //封装skuS
        return null;
    }


    private void checkProductDetail(ProductDetailsResponse productDetail) {
        if (productDetail == null) {
            throw new ServiceException("商品上架失败，商品数据为空");
        }
        List<MallProductSkuInfo> skuList = productDetail.getSkuList();
        if (skuList == null || skuList.size() == 0) {
            throw new ServiceException("商品上架失败，商品Sku为空");
        }

    }


}
